package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.entity.Teacher;
import com.example.haoqisystem.entity.Worker;
import com.example.haoqisystem.request.CreateTeacherRequest;
import com.example.haoqisystem.request.UpdateTeacherRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.respository.TeacherRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
public class TeacherService {
    private final TeacherRepository teacherRepository;

    //验证密码
    public boolean isPassword(String pwd){
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,16}$";
        return pwd.matches(regex);
    }

    //验证邮箱格式
    public boolean isEmail(String email){
        String regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(regex);
    }

    //验证手机号
    public boolean isValidPhoneNumber(String phoneNumber) {
        // 移除号码中的空格、括号、破折号等特殊字符
        String cleanedNumber = phoneNumber.replaceAll("[\\s()-]+", "");

        // 验证手机号格式
        String regex = "^(\\+?\\d{1,3})?[-.\\s]?\\(?\\d{1,4}\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$";
        return cleanedNumber.matches(regex);
    }

    //新增教师
    public BaseResponse<Teacher> register(CreateTeacherRequest request) {
        //验证邮箱
        if(request.getEmail()!=null&&!request.getEmail().equals("")) {
            if (!isEmail(request.getEmail())) {
                return new BaseResponse<>("邮箱格式错误！", false, null);
            }
        }
        if(request.getTelephone()!=null&&!request.getTelephone().equals("")) {
            if (!isValidPhoneNumber(request.getTelephone())) {
                return new BaseResponse<>("手机号格式错误！", false, null);
            }
        }
        try{
            Teacher teacher=new Teacher();
            BeanUtil.copyProperties(request,teacher, CopyOptions.create().setIgnoreNullValue(true));
            Teacher teacher1=teacherRepository.save(teacher);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,teacher1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //更新
    public BaseResponse<Teacher> update(UpdateTeacherRequest request) {
        if(request.getId()==null){
            return new BaseResponse<>("需要讲师id！",false,null);
        }
        try{
            Optional<Teacher> optionalTeacher=teacherRepository.findByIdAndDeletedFalse(request.getId());
            if(!optionalTeacher.isPresent()){
                return new BaseResponse<>("该讲师不存在！",false,null);
            }
            Teacher teacher=optionalTeacher.get();
            BeanUtil.copyProperties(request,teacher,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,teacherRepository.save(teacher));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //查询列表
    public BaseResponse<List<Teacher>> queryList(String name, String jobTitle, String skillField,Long id) {
        try{
            Specification<Teacher> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(name!=null&&!name.equals("")){
                    String nameLike="%"+name+"%";
                    predicates.add(builder.like(root.get("name"),nameLike));
                }
                if(jobTitle!=null&&!jobTitle.equals("")){
                    String jobLike="%"+jobTitle+"%";
                    predicates.add(builder.like(root.get("jobTitle"),jobLike));
                }
                if(skillField!=null&&!skillField.equals("")){
                    String skillLike="%"+skillField+"%";
                    predicates.add(builder.like(root.get("skilledField"),skillLike));
                }
                if(id!=null&&!id.equals("")){
                    predicates.add(builder.equal(root.get("id"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<Teacher> list=teacherRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //跟据id查询教师详情
    public BaseResponse<Teacher> detail(Long id) {
        try{
            Optional<Teacher> teacherOptional=teacherRepository.findByIdAndDeletedFalse(id);
            if(!teacherOptional.isPresent()){
                return new BaseResponse<>("该教师不存在！",false,null);
            }
            Teacher teacher=teacherOptional.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,teacher);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除教师
    public BaseResponse<String> delete(Long id) {
        try{
            Optional<Teacher> teacherOptional=teacherRepository.findByIdAndDeletedFalse(id);
            if(!teacherOptional.isPresent()){
                return new BaseResponse<>("该教师不存在或已被删除！",false,null);
            }
            Teacher teacher=teacherOptional.get();
            teacher.setDeleted(true);
            teacherRepository.save(teacher);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,null);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //教师登陆
    public BaseResponse<Teacher> login(String account, String password) {
        try{
            Optional<Teacher> teacherOptional=teacherRepository.findByAccountAndDeletedFalse(account);
            if(!teacherOptional.isPresent()){
                return new BaseResponse<>("该教师不存在！",false,null);
            }
            Teacher teacher=teacherOptional.get();
            if(!password.equals(teacher.getPassword())){
                return new BaseResponse<>("登录失败，密码错误！",false,null);
            }
            return new BaseResponse<>("登录成功！",true,teacher);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //重置密码
    public BaseResponse<String> resetPassword(Long id, String password) {
            try{
                Optional<Teacher> teacherOptional=teacherRepository.findById(id);
                if(!teacherOptional.isPresent()){
                    return new BaseResponse<>("该用户不存在！", false, null);
                }
                Teacher teacher=teacherOptional.get();
                if(teacher.getPassword().equals(password)){
                    return new BaseResponse<>("请勿输入重复的密码！", false, null);
                }
                teacher.setPassword(password);
                teacherRepository.save(teacher);
                return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,null);
            }catch (Exception e){
                return new BaseResponse<>(e.toString(),false,null);
            }
    }

}
